import * as Cesium from "cesium";

type Option = {
    time: number,
    percent: number,
    movespeed: number,
    red: number,
    green: number,
    blue: number
}
export default function flowLine(viewer: Cesium.Viewer, position: number[], option = {}) {
    const optionInt: Option = {
        time: 5.0,
        percent: 0.2,
        movespeed: 0.5,
        red: 0,
        green: 0,
        blue:0
    }
    const options = {...optionInt, ...option}
    const {time, percent, movespeed, red, blue, green} = options
    var material = new Cesium.Material({
        fabric: {
            uniforms: {
                u_itime: time,
                u_trailpercent: percent,
                u_trailmovespeed: movespeed,
            }
        }
    });

    var primitive = new Cesium.Primitive({
        geometryInstances: new Cesium.GeometryInstance({
            geometry: new Cesium.PolylineGeometry({
                positions: Cesium.Cartesian3.fromDegreesArrayHeights(position),
                width: 8.0,
                vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
                colorsPerVertex: true,
                colors: [
                    new Cesium.Color(0.1, 0.0, 0.0, 1.0),
                    new Cesium.Color(0.5, 0.0, 0.0, 1.0),
                    new Cesium.Color(1.0, 0.0, 0.0, 1.0)
                ],
            }),
        }),
        appearance: new Cesium.PolylineColorAppearance({
            translucent: false,
            fragmentShaderSource: `
            precision highp float;
            varying vec4 v_color;
            void main(){
              float r=v_color.r-u_itime_0*u_trailmovespeed_2;
              float dist=smoothstep(0.0,u_trailpercent_1,mod(r,u_trailpercent_1));
              gl_FragColor=mix(vec4(0.8),vec4(${red},${green},${blue},1.0),dist);
            }
        `,
        }),
    });

    primitive.appearance.material = material;

    viewer.scene.primitives.add(primitive);

    viewer.scene.preRender.addEventListener(function (s: any, t: { secondsOfDay: number; }) {
        primitive.appearance.material.uniforms.u_itime = Cesium.JulianDate.now().secondsOfDay - t.secondsOfDay;
    });
}